package com.xmg.p2p.base.controller;

import com.xmg.p2p.base.domain.Account;
import com.xmg.p2p.base.domain.Logininfo;
import com.xmg.p2p.base.domain.Userinfo;
import com.xmg.p2p.base.interceptor.RequireLogin;
import com.xmg.p2p.base.service.IAccountService;
import com.xmg.p2p.base.service.IUserinfoService;
import com.xmg.p2p.base.util.JSONResult;
import com.xmg.p2p.base.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * lcd  2020/5/8
 * Description:
 */
@Controller
public class PersonalController {
    @Autowired
    private IUserinfoService userinfoService;
    @Autowired
    private IAccountService accountService;


    @RequireLogin
    @RequestMapping("/personal")
    public String personalCenter(Model model) {
        Logininfo logininfo = UserContext.getLogininfo();
        Userinfo userinfo = userinfoService.findById(logininfo.getId());
        Account account = accountService.findById(logininfo.getId());
        model.addAttribute("userinfo", userinfo);
        model.addAttribute("account", account);
        return "personal";
    }

    //校验手机号，验证码，时间间隔90秒
    @RequireLogin
    @RequestMapping("bindPhone")
    @ResponseBody
    public JSONResult bindPhone(String phoneNumber, String verifyCode) {
        JSONResult jsonResult = new JSONResult();
        try{
            userinfoService.bindPhone(phoneNumber,verifyCode);
            jsonResult.setMsg("手机绑定成功");
        }catch (Exception e){
            jsonResult.setSuccess(false);
            jsonResult.setMsg(e.getMessage());
        }
        return jsonResult;
    }

    //发送邮件
    @RequireLogin
    @RequestMapping("sendEmail")
    @ResponseBody
    public JSONResult sendEmail(String email){
        JSONResult jsonResult = new JSONResult();
        try{
            userinfoService.sendVerifyCode(email);
            jsonResult.setMsg("邮件发送成功");
        }catch (Exception e){
            jsonResult.setSuccess(false);
            jsonResult.setMsg(e.getMessage());
        }
        return jsonResult;
    }

    //从邮箱进到这里绑定邮箱
    @RequestMapping("bindEmail")
    public String bindEmail(String key,Model model){
        try{
            userinfoService.bindEmail(key);
            model.addAttribute("success",true);
        }catch (Exception e){
            model.addAttribute("success",false);
            model.addAttribute("msg",e.getMessage());
        }
        return "checkmail_result";
    }
}
